#region Imported Namespaces
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

using PHSRAG.Insight21.SearchContext;
using Calendar = PHSRAG.WebControls.Calendar;
using DataAccess = PHSRAG.Utility.DataAccess;
using SessionCachePolicy = PHSRAG.Insight21.Policy.SessionCachePolicy;
using Policy = PHSRAG.Insight21.Policy;
using UserContext = PHSRAG.Insight21.Context.UserContext;
using Constants = PHSRAG.Insight21.InsightUtilities.Constants;
#endregion

namespace PHSRAG.Insight21.InsightWebControls
{
	#region Class LaborDistributionSearch
	/// <summary>
	/// The LaborDistributionSearch control is used by Agreement pages.
	/// </summary>
	[ToolboxData("<{0}:LaborDistributionSearch runat=server />"), Designer(typeof(LaborDistributionSearchDesigner))]
	public class LaborDistributionSearch : BaseSearch, INamingContainer, ISearch
	{
		#region Instance Variables
		private Policy.ICachePolicy	cachePolicy;
        //private TextBox employeeFirstName;
        //private TextBox employeeLastName;
		private TextBox		jobCode;
		//private DropDownList fundStatus;
		//private DropDownList payFrequencyType;
        private PHSRAG.WebControls.Calendar PaySalaryDateFrom;
        private PHSRAG.WebControls.Calendar PaySalaryDateTo;
		private PHSRAG.WebControls.Calendar retroSalaryDateFrom;
		private PHSRAG.WebControls.Calendar retroSalaryDateTo;
		private ControlCollection	controlCollection;
      	

		#endregion

		#region ISearch Members
		/// <summary>
		/// Reset the internal search state. This involves setting the value for all controls to their default values
		/// and resetting the cached state of the search context.
		/// </summary>
		public void Reset()
		{
			ResetControls(controlCollection);
            retroSalaryDateFrom.Reset();
			retroSalaryDateTo.Reset();
			LaborDistributionSearchContext searchContext = (LaborDistributionSearchContext)cachePolicy.GetCachedObject(LaborDistributionSearchContext.CacheKey);
			searchContext.Reset(Page.Request.Url.ToString());
		}

		/// <summary>
		/// Get the search criteria from the common search context.
		/// </summary>
		public SearchCriteria SearchCriteria
		{
			get
			{
                return ((LaborDistributionSearchContext)cachePolicy.GetCachedObject(LaborDistributionSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString());
			}
		}


		/// <summary>
		/// Get the search criteria. This is done by collecting the current values in all controls, storing them in the
		/// LaborDistributionSearchContext, and then returning the search criteria.
		/// </summary>
		public SearchCriteria UpdateSearchCriteria()
		{
			UserContext userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
			return GetSearchCriteria(userContext.DomainUserId, controlCollection);
		}
		#endregion

		#region Public Properties
		
		#endregion

		#region Protected Properties
		/// <summary>
		/// Determine if the control is in design mode. It is if there is not HTTP context.
		/// </summary>
		protected static bool IsDesignMode
		{
			get { return HttpContext.Current == null; }
		}
		#endregion

		#region Virtual Methods
		/// <summary>
		/// Invoked by the method which builds the HTML representation of the control tree. Derived classes would typically
		/// return the HTML to be inserted into the stream AFTER the indicated row.
		/// </summary>
		/// <param name="currentRowNumber">The number (starting from 1) of the row that the HTML returned by this method
		/// would be inserted at.
		/// </param>
		/// <returns>HTML string to add at row number currentRowNumber</returns>
		protected virtual string GetHTML(int currentRowNumber)
		{
			return string.Empty;
		}
		#endregion 

		#region Overrides
		/// <summary>
		/// Create all controls. Notice that the creation is more than just instantiating the controls. It also involves
		/// in generating the underlying HTML so that the controls shows up per the need.
		/// </summary>
		protected override void CreateChildControls()
		{
			CreateControls();
			GenerateControlTree();
		}
		/// <summary>
		/// Initializes the cachepolicy. Create and cache a LaborDistributionSearchContext object if necessary.
		/// Note that controls whose state must persist in the view state MUST be created BEFORE OnInit completes. We do
		/// this simply by invoking EnsureChildControls().
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnInit(EventArgs e)
		{
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
			LaborDistributionSearchContext searchContext = cachePolicy.GetCachedObject(LaborDistributionSearchContext.CacheKey) as LaborDistributionSearchContext;
			if (searchContext == null)
			{
				searchContext = new LaborDistributionSearchContext(cachePolicy);
				searchContext.Load(DataAccess.ConnectionString);
				searchContext.Cache();
			}
			EnsureChildControls();
			base.OnInit(e);
			searchContext.GetSearchCriteria(Page.Request.Url.ToString(), controlCollection);
		}
		/// <summary>
		/// Initialize the contents of all controls on first load. If the LaborDistributionSearchContext is not cached yet, a
		/// new instance is created and cached. 
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnLoad(EventArgs e)
		{
			if (!Page.IsPostBack)
			{	
				int defaultSelectedIndex = 0;
                int defaultStatusSelectedIndex = 1; //added 10/22/2007 for "Active" as default - TrackIt 6940
                LaborDistributionSearchContext searchContext = (LaborDistributionSearchContext)cachePolicy.GetCachedObject(LaborDistributionSearchContext.CacheKey);	
				//LoadDropDownList(fundStatus, searchContext.StatusData, "ID", defaultStatusSelectedIndex);
				//LoadDropDownList(payFrequencyType, searchContext.PayFrequencyTypeData, "ID", defaultSelectedIndex);
            	SetControlState(searchContext.GetSearchCriteria(Page.Request.Url.ToString()));
			}
		}

        /// <summary>
        /// Set the state for all constituent controls, and register a client script block for the express purpose of
        /// validating the date ranges of all paired Calendar controls in this search block.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        /// <remarks>
        /// <protocolId>Why are the actions taken in this method not being done on control load?</protocolId>
        /// <protocolId>During the non-postback construction of the control, the OnLoad method is invoked BEFORE the
        /// CreateChildControls method. The actual creation of constitutent controls are done within the context of
        /// the CreateChildControls methos. Setting the state of control relies on (obviously) the fact that the controls
        /// have been created. So, setting the state in OnLoad for the non-postback condition would fail.</protocolId>
        /// <protocolId>Interestingly, the sequence of method invocations reverses on postback: CreateChildControls is invoked
        /// before OnLoad.</protocolId>
        /// </remarks>
        protected override void OnPreRender(EventArgs e)
        {
            if (!IsDesignMode)
            {
                if (!Page.ClientScript.IsClientScriptBlockRegistered(Constants.ValidateDateRangeScriptKey))
                {
                    string script = string.Format(
                        "<script language=\"javascript\">\n" +
                        "function ValidateDateRange()\n" +
                        "{{\n" +
                        "\tif (document.getElementById(\"{0}\") != null)\n" +
                        "\t\tvar retroSalaryFromText = document.getElementById(\"{0}\").value;\n" +
                        "\tif (document.getElementById(\"{1}\") != null)\n" +
                        "\t\tvar retroSalaryToText = document.getElementById(\"{1}\").value;\n" +
                        "\tif (retroSalaryFromText != null && retroSalaryFromText != \"\" && retroSalaryToText != null && retroSalaryToText != \"\")\n" +
                        "\t{{\n" +
                        "\t\tvar retroSalaryFromDate = new Date(retroSalaryFromText);\n" +
                        "\t\tvar retroSalaryToDate = new Date(retroSalaryToText);\n" +
                        "\t\tif (retroSalaryFromDate > retroSalaryToDate)\n" +
                        "\t\t{{\n" +
                        "\t\t\talert('Retro Salary From Date cannot be after Retro Salary To Date.');\n" +
                        "\t\t\tdocument.getElementById(\"{1}\").focus();\n" +
                        "\t\t\treturn false;\n" +
                        "\t\t}}\n" +
                        "\t\treturn true;\n" +
                        "\t}}\n" +
                        "\treturn true;\n" +
                        "}}\n" +
                        "</script>\n",
                        (retroSalaryDateFrom == null) ? "" : retroSalaryDateFrom.SelectedDateClientId,
                        (retroSalaryDateTo == null) ? "" : retroSalaryDateTo.SelectedDateClientId);

                    Page.ClientScript.RegisterClientScriptBlock(GetType( ), Constants.ValidateDateRangeScriptKey, script);
                }
            }

            base.OnPreRender (e);
        }

		/// <summary>
		/// Render the control. Note that we simply ensure that all child controls are created, and then delegate the
		/// call back to the base class.
		/// </summary>
		/// <param name="writer">The writer to use for rendering</param>
		protected override void Render(HtmlTextWriter writer)
		{
			EnsureChildControls();
			base.Render(writer);
		}
		#endregion

		#region Private Methods
		/// <summary>
		/// Create all controls in the CommonSearch.
		/// </summary>
		private void CreateControls()
		{
			Controls.Clear();
			controlCollection = new ControlCollection(this);

            PaySalaryDateFrom = new PHSRAG.WebControls.Calendar();
            PaySalaryDateFrom.ID = "PaySalaryDateFrom";
            PaySalaryDateFrom.Prompt = CommonSearch.SelectPrompt;
            PaySalaryDateFrom.Attributes["Label"] = "Pay Date From";
            controlCollection.Add(PaySalaryDateFrom);

            PaySalaryDateTo = new PHSRAG.WebControls.Calendar();
            PaySalaryDateTo.ID = "PaySalaryDateTo";
            PaySalaryDateTo.Prompt = CommonSearch.SelectPrompt;
            PaySalaryDateTo.Attributes["Label"] = "Pay Date To";
            controlCollection.Add(PaySalaryDateTo);

            retroSalaryDateFrom = new PHSRAG.WebControls.Calendar();
            retroSalaryDateFrom.ID = "retroSalaryDateFrom";
            retroSalaryDateFrom.Prompt = CommonSearch.SelectPrompt;
            retroSalaryDateFrom.Attributes["Label"] = "Retro Salary Date From";
            controlCollection.Add(retroSalaryDateFrom);
			
			retroSalaryDateTo = new PHSRAG.WebControls.Calendar();
            retroSalaryDateTo.ID = "retroSalaryDateTo";
			retroSalaryDateTo.Prompt = CommonSearch.SelectPrompt;
            retroSalaryDateTo.Attributes["Label"] = "Retro Salary Date To";
            controlCollection.Add(retroSalaryDateTo);


           

            //employeeFirstName = new TextBox();
            //employeeFirstName.ID = "employeeFirstName";
            //employeeFirstName.CssClass = "DataInput";
            //employeeFirstName.Attributes["Label"] = "Employee First Name";
            //controlCollection.Add(employeeFirstName);


            //employeeLastName = new TextBox();
            //employeeLastName.ID = "employeeLastName";
            //employeeLastName.CssClass = "DataInput";
            //employeeLastName.Attributes["Label"] = "Employee Last Name";
            //controlCollection.Add(employeeLastName);

            //fundStatus = new DropDownList();
            //fundStatus.ID = "status";
            //fundStatus.CssClass = "DataInput";
            //fundStatus.Attributes["Label"] = "Status";
            //controlCollection.Add(fundStatus);
            //fundStatus.Visible = false;

            //payFrequencyType = new DropDownList();
            //payFrequencyType.ID = "payFrequencyType";
            //payFrequencyType.CssClass = "DataInput";
            //payFrequencyType.Attributes["Label"] = "Pay Frequency Type";
            //controlCollection.Add(payFrequencyType);
            
            

			jobCode = new TextBox();
			jobCode.ID = "jobCode";
			jobCode.CssClass = "DataInput";
			jobCode.Attributes["Label"] = "Job Code";
            controlCollection.Add(jobCode);
		
			
		}
		/// <summary>
		/// Create a table hosted by the first column of the first row of the first table. 
		/// The table contains the following: 
		/// Row 1 Col 1: Employee # Label 
		/// Row 1 Col 2: Employee TextBox
		/// Row 3 Col 1: Effective Salary Date From Label
		/// Row 3 Col 2: Effective Salary Date From Calendar 
		/// Row 4 Col 1: View Employees Ending in Label	
		/// Row 4 Col 2: View Employees Ending in Dropdown
		/// Row 5 Col 1: View By Fiscal Year Label
		/// Row 5 Col 2: View By Fiscal Year Dropdown
		/// </summary>

		private Table GenerateControlTreeForFirstSection()
		{
			Table t = new Table();
			t.CssClass = "Search";
			t.CellSpacing = t.CellPadding = 5;
            ////Employee First Name
            //TableRow r1 = new TableRow();
            //t.Rows.Add(r1);
            //TableCell r1c1 = new TableCell();
            //r1c1.Attributes["align"] = "right";
            //r1c1.Text = "<nobr>Employee&nbsp;First&nbsp;Name:</nobr>";
            //r1.Cells.Add(r1c1);
            //TableCell r1c2 = new TableCell();
            //r1.Cells.Add(r1c2);
            //r1c2.ColumnSpan = 3;
            //r1c2.Controls.Add(employeeFirstName);



            TableRow r2 = new TableRow();
            t.Rows.Add(r2);
			TableCell r2c1 = new TableCell();
			r2c1.Attributes["align"] = "right";
            r2c1.Text = "<nobr>Job&nbsp;Code:</nobr>"; 
			r2.Cells.Add(r2c1);
			TableCell r2c2 = new TableCell();
			r2.Cells.Add(r2c2);
			r2c2.ColumnSpan = 3;
            r2c2.Controls.Add(jobCode);

			

			TableRow r3 = new TableRow();
			t.Rows.Add(r3);
			TableCell r3c1 = new TableCell();
			r3c1.Attributes["align"] = "right";
			r3c1.Text = "<nobr>Pay&nbsp;Date&nbsp;From:</nobr>";
			r3.Cells.Add(r3c1);

			TableCell r3c2 = new TableCell();
			r3.Cells.Add(r3c2);
            r3c2.Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)PaySalaryDateFrom);
			
			TableCell r3c3 = new TableCell();
			r3c3.Attributes["align"] = "right";
			r3c3.Text = "To:"; 
			r3.Cells.Add(r3c3);

			TableCell r3c4 = new TableCell();
			r3.Cells.Add(r3c4);
            r3c4.Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)PaySalaryDateTo);
			
			return t;
		}

		/// <summary>
		/// Create a table hosted by the Second column of the first row of the first table. 
		/// The table contains the following: 
		/// Row 1 Col 1: Job Code  Label 
		/// Row 1 Col 2: Job Code TextBox
		/// Row 2 Col 1: Pay Frequency Type Label
		/// Row 2 Col 2: Pay Frequency Type DropDown
		/// Row 3 Col 1: Status Label
		/// Row 3 Col 2: Status DropDown
		/// </summary>
		private Table GenerateControlTreeForSecondSection()
		{
			Table t = new Table();
			t.CssClass = "Search";
			t.CellSpacing = t.CellPadding = 5;
			

            ////Employee Last Name
            //TableRow r1 = new TableRow();
            //t.Rows.Add(r1);
            //TableCell r1c1 = new TableCell();
            //r1c1.Attributes["align"] = "right";
            //r1c1.Text = "<nobr>Employee&nbsp;Last&nbsp;Name:</nobr>";
            //r1.Cells.Add(r1c1);
            //TableCell r1c2 = new TableCell();
            //r1.Cells.Add(r1c2);
            //r1c2.Controls.Add(employeeLastName);


            TableRow r4 = new TableRow();
            t.Rows.Add(r4);
            TableCell r4c1 = new TableCell();
            r4c1.Attributes["align"] = "right";
            r4c1.Text = "<nobr>Retro&nbsp;Salary&nbsp;Date&nbsp;From:</nobr>";
            r4.Cells.Add(r4c1);

            TableCell r4c2 = new TableCell();
            r4.Cells.Add(r4c2);
            r4c2.Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)retroSalaryDateFrom);

            TableCell r4c3 = new TableCell();
            r4c3.Attributes["align"] = "right";
            r4c3.Text = "To:";
            r4.Cells.Add(r4c3);

            TableCell r4c4 = new TableCell();
            r4.Cells.Add(r4c4);
            r4c4.Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)retroSalaryDateTo);


            //TableRow r3 = new TableRow();
            //t.Rows.Add(r3);
            //TableCell r3c1 = new TableCell();
            //r3c1.Attributes["align"] = "right";
            //r3c1.Text = "<nobr>Pay&nbsp;Frequency&nbsp;Type:</nobr>"; 
            //r3.Cells.Add(r3c1);
            //TableCell r3c2 = new TableCell();
            //r3.Cells.Add(r3c2);
            //r3c2.Controls.Add(payFrequencyType);

            //TableRow r4 = new TableRow();
            //t.Rows.Add(r4);
            //TableCell r4c1 = new TableCell();
            //r4c1.Attributes["align"] = "right";
            //r4c1.Text = "<nobr>Status:</nobr>"; 
            //r4.Cells.Add(r4c1);
            //TableCell r4c2 = new TableCell();
            //r4.Cells.Add(r4c2);
            //r4c2.Controls.Add(fundStatus);
			
			return t;
		}

		/// <summary>
		/// Setup the control tree to reflect the actual (and exact) layout of the controls within the CommonSearch.
		/// </summary>
		private void GenerateControlTree()
		{
            string searchClientId = ((Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey]).GetCachedObject(Constants.SearchButtonClientIDKey) as string;
            if (searchClientId == null)
                searchClientId = "expandingPanel_commonSearch_search";

			Table t1 = new Table();
			t1.CssClass = "Search";
			t1.CellSpacing = t1.CellPadding = 5;
            t1.Attributes.Add("onkeypress", "return ClickButton(event, '" + searchClientId + "')");
            Controls.Add(t1);

			TableRow t1r1 = new TableRow();
			t1.Rows.Add(t1r1);

			TableCell t1r1c1 = new TableCell();
			t1r1c1.Attributes["valign"] = "top";
			t1r1.Cells.Add(t1r1c1);
			t1r1c1.Controls.Add(GenerateControlTreeForFirstSection());

			TableCell separator = new TableCell();
			separator.Attributes["style"] = "border-left: thin solid #c0c0c0";
			separator.Controls.Add(new LiteralControl("&nbsp;"));
			t1r1.Cells.Add(separator);
			
			TableCell t1r1c2 = new TableCell();
			t1r1c2.Attributes["valign"] = "top";
			t1r1.Cells.Add(t1r1c2);
			t1r1c2.Controls.Add(GenerateControlTreeForSecondSection());
		}


		#endregion

		#region Internal Methods
		/// <summary>
		/// This method is ONLY invoked by the associated designer to show the control contents at design time.
		/// </summary>
		internal void Design()
		{
			EnsureChildControls();
		}
		#endregion
	}
	#endregion

	#region Class PagerDesigner
	/// <summary>
	/// Designer associated with the LaborDistributionSearch control.
	/// </summary>
	/// <remarks>
	/// This class cannot be used directly.
	/// </remarks>
	public class LaborDistributionSearchDesigner : ControlDesigner
	{
		#region Overrides
		/// <summary>
		/// Force the control to create its child controls for display at design time.
		/// </summary>
		/// <returns>HTML representation of the control</returns>
		public override string GetDesignTimeHtml()
		{
			((LaborDistributionSearch)Component).Design();
			return base.GetDesignTimeHtml();
		}
		#endregion
	}
	#endregion
}

// --- EOF ---
